package com.study.flink.java.day05_state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

import java.util.Properties;

/**
 * 观察OperatorState和KeyedState
 * kafka消费者消费数据记录偏移量，消费者对应SubTask使用OperatorState记录偏移量
 * keyBy之后，进行聚合操作，进行历史数据累加，这些subTask使用累加分组后的历史数据就是KeyedState
 */
public class OperatorStateAndKeyedStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //5秒钟更新State
        env.enableCheckpointing(5000);

        //实现EXACTLY_ONCE，必须记录偏移量
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);

        //把任务停掉之后，依然保存之前的checkpoint
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

        // kafka的partitions有3个，对应有3个source
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "node02:9092"); //kafka的broker地址
        props.setProperty("group.id", "gid-wc10");//指定组ID
        props.setProperty("auto.offset.reset", "earliest");//没有记录偏移量，第一次从最开始消费
        //不自动提交偏移量，而是交给Flink通过Checkpointing管理偏移量
        props.setProperty("enable.auto.commit", "false");

        // 用kafka的并行source，每一个组都要满足条件才会触发
        FlinkKafkaConsumer<String> wc10 = new FlinkKafkaConsumer<>("wc10", new SimpleStringSchema(), props);
        DataStream<String> lines = env.addSource(wc10);

        SingleOutputStreamOperator<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                // 切分 压平
                String[] words = line.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                // (单词,次数)
                return Tuple2.of(s, 1);
            }
        });

        // 为了保证程序出现问题可以继续累加，要记录分组聚合的中间结果
        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndCount.keyBy(0).sum(1);

        summed.print();

        env.execute("OperatorStateAndKeyedStateDemo-java");

    }




}
